#include "fun.h"


void InitDisplay(void)
{
  	OLED_ShowString(45,0,"AD9833");
	OLED_ShowString(8,4,"Freq:          ");
	OLED_ShowString(112,4,"Hz");
	OLED_ShowNum(45,4,freq,8,16);
}

/*
	Increment rule
0-100 		inc 1
100-1k	    inc 5
1k-10k	 	inc 50
10k-100k    inc 500
100k-1M     inc 5000
*/
u16 Increment(void)
{
  
	static u16 inc=0;
	if(freq<100)
	{
	  inc=1;
	}
	else if(freq<1000)
	{
	  inc=5;
	}
	else if(freq<10000)
	{
	  inc=50;
	}
	else if(freq<100000)
	{
	  inc=500;
	}
	else if(freq<1000000)
	{
	  inc=5000;
	}
	else
	{
	  inc=10000;
	}

	return inc;
}


void checkFreq(void)
{
	if(freq>2000000)
	{
		freq=1;
	}
	else if(freq<1)
	{
		freq=2000000;
	}
}

void showIntelligentFreq(void)
{
	if(freq<1000)
	{
		OLED_ShowNum(45,6,freq,8,16);
		OLED_ShowChar(109,6,' ');
	}
	else if(freq<100000)
	{
		OLED_ShowFloat(64,6,freq/1000.0,'k',2);
	}
	else if(freq<1000000)
	{
		OLED_ShowNum(49,6,freq/1000,7,16);
		OLED_ShowChar(104,6,'k');
	}
	else
	{
		OLED_ShowFloat(64,6,freq/1000000.0,'M',2);
	}
	OLED_ShowString(112,4,"Hz");
	OLED_ShowString(112,6,"Hz");
}


void setPWM(void)
{
	if(pwmduty>20000)
	{
	  	pwmduty=0;
	}
	else if(pwmduty<0)
	{
	  	pwmduty=20000;
	}
	OLED_ShowFloat(70,4,pwmduty/1000.0,0,1);
	OLED_ShowNum(84,6,pwmduty/200,3,16);
	TIM2_SetCompare1(pwmduty);
}

void keyEvent(u8 inc)
{
    u8 i=0;
	u8 pwmflag=key1%4;
	if(pwmflag==3)
	{
		if(inc)pwmduty+=100;
		else pwmduty-=100;
		setPWM();
	}
	else
	{
		first=1;
		if(inc)freq+=Increment();
		else freq-=Increment();
		
		checkFreq();
		OLED_ShowNum(45,4,freq,8,16);
		showIntelligentFreq();
	}
	  
	
	while(!KEY2||!KEY3)
	{
		for(;i<40;++i)
		{
			if(KEY2&&KEY3)
			{
				return;
			}
			delay_ms(10);
		}
		
		if(pwmflag==3)
		{
			if(inc)pwmduty+=100;
			else pwmduty-=100;
			setPWM();
			delay_ms(25);
			
		}
		else
		{
			if(inc)freq+=Increment();
			else freq-=Increment();
			checkFreq();
			OLED_ShowNum(45,4,freq,8,16);
			showIntelligentFreq();
			delay_ms(10);
		}
	}
}




